//
//  AppDelegate.m
//  HNBaseProject
//
//  Created by Apple on 2021/7/12.
//

#import "AppDelegate.h"
#import "AppDelegate+SDK.h"
#import "DCTabbarController.h"
#import "ViewController.h"
#import "DCNavigationController.h"
#import "MXLoginController.h"
#import <WXApi.h>
#import <UserNotifications/UserNotifications.h>
@interface AppDelegate () <WXApiDelegate,JPUSHRegisterDelegate>
@property (nonatomic,strong) DCTabbarController * tabbarVC;

@end

@implementation AppDelegate

+ (AppDelegate *)shareDelegate {
    return (AppDelegate *)[UIApplication sharedApplication].delegate;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    self.registrationID = @"";
    // 初始化第三方SDK
//    [self initSDKWithOptions:launchOptions];
    [WXApi registerApp:DCWX_AppKey universalLink:DCWX_UniversalLinks];
    
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert | JPAuthorizationOptionBadge | JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];

    BOOL apsForProduction = NO;
#ifdef DEBUG
    apsForProduction = NO;
#else
    apsForProduction = YES;
#endif

    [JPUSHService setupWithOption:launchOptions appKey:DCJPush_AppKey
                          channel:@"App Store"
                 apsForProduction:apsForProduction
            advertisingIdentifier:nil];

    // 获取 registrationID]
    MJWeakSelf
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        NSLog(@"resCode : %d,registrationID: %@",resCode,registrationID);
        weakSelf.registrationID = registrationID;
        [JPUSHService setAlias:registrationID completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
            
        } seq:0];
    }];
    
//    [[DCHelpTool shareClient] dc_bindAlies];
    
    //这里判断用户信息
    MXUserInfoModel *model = [DCCacheTool getCurrentUserInfo];
    if (model&&model.ID.length >0) {
        self.window.rootViewController = [[DCNavigationController alloc] initWithRootViewController:[[DCTabbarController alloc] init]];
    } else {
        self.window.rootViewController = [[DCNavigationController alloc] initWithRootViewController:[[MXLoginController alloc] init]];
    }
    [self.window makeKeyAndVisible];
    
    return YES;
}

- (void)loginStateChange:(NSNotification *)notification
{
    BOOL bol = [notification.object boolValue];
    if (bol) {
        self.tabbarVC = [[DCTabbarController alloc] init];
        UINavigationController * navigationController = [[UINavigationController alloc] initWithRootViewController:self.tabbarVC];
        self.window.rootViewController = navigationController;
        
        [[DCHelpTool shareClient] dc_bindAlies];
        
    }else{
        
//        LoginVC * loginVC = [[LoginVC alloc] init];
//        UINavigationController * navigationController = [[UINavigationController alloc] initWithRootViewController:loginVC];
//        self.window.rootViewController = navigationController;
//        
//        [[DCHelpTool shareClient] dc_deleteAlies];
        
//        DCTestVC * testVC = [[DCTestVC alloc] init];
//        self.window.rootViewController = testVC;
    }
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options
{
    NSLog(@"======openURL:%@,%@,%@,%@",url.absoluteString,url.scheme,url.host,url.port);

    if([url.scheme isEqualToString:DCWX_AppKey]){
        return [WXApi handleOpenURL:url delegate:self];
    }
    return YES;
}
- (BOOL)application:(UIApplication *)application
  continueUserActivity:(NSUserActivity *)userActivity
   restorationHandler:(nonnull void (^)  (NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler{
    NSLog(@"======continueUserActivity:%@",userActivity.webpageURL.absoluteString);
//    if([userActivity.webpageURL.scheme isEqualToString:DCWX_AppKey]){
        return [WXApi handleOpenUniversalLink:userActivity delegate:self];
//    }
    return YES;
}

#pragma mark - 重写微信回调
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    NSLog(@"======handleOpenURL:%@",url.absoluteString);
    if([url.scheme isEqualToString:DCWX_AppKey]){
        return [WXApi handleOpenURL:url delegate:self];
    }
    return YES;
}

// 支持所有iOS系统
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
//    //6.3的新的API调用，是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响
//    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
//    if (!result) {
//
//        NSLog(@"url1 -- %@",url.absoluteString);
//
//        // 支付宝支付
//        if ([url.host isEqualToString:@"safepay"]) {
//            //跳转支付宝钱包进行支付，处理支付结果
//            [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
//                NSLog(@"result = %@",resultDic);
//                [[NSNotificationCenter defaultCenter]postNotificationName:DC_NotificationName_Alipay object:self userInfo:resultDic];
//            }];
//            return YES;
//        }
//
//        // 微信支付回调
//        return [WXApi handleOpenURL:url delegate:self];
//    }
//    return result;
    
    return YES;
}

- (void)onResp:(BaseResp *)resp {
    switch (resp.errCode) {
        case 0:
            if([resp isKindOfClass:[SendAuthResp class]]) { //判断是否是微信登录
                SendAuthResp*aresp = (SendAuthResp*)resp;
                [[NSNotificationCenter defaultCenter] postNotificationName:@"WXLoginNotificaton" object:@{@"code":aresp.code}];
            }
            break;
        case -1:
            break;
        case -2:
            if([resp isKindOfClass:[SendAuthResp class]]) {//判断是否是微信登录
                [SVProgressHUD showErrorWithStatus:@"微信登录授权取消"];
                [SVProgressHUD dismissWithDelay:1.5];
            }
        default:
            break;
    }
}

//- (UISceneConfiguration *)application:(UIApplication *)application configurationForConnectingSceneSession:(UISceneSession *)connectingSceneSession options:(UISceneConnectionOptions *)options {
//    // Called when a new scene session is being created.
//    // Use this method to select a configuration to create the new scene with.
//    return [[UISceneConfiguration alloc] initWithName:@"Default Configuration" sessionRole:connectingSceneSession.role];
//}
//
//
//- (void)application:(UIApplication *)application didDiscardSceneSessions:(NSSet<UISceneSession *> *)sceneSessions {
//    // Called when the user discards a scene session.
//    // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
//    // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
//}


- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    // Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}

# pragma mark- JPUSHRegisterDelegate

// iOS 12 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification API_AVAILABLE(ios(10.0)){
  if (notification && [notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
    //从通知界面直接进入应用
  }else{
    //从通知设置界面进入应用
  }
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
  // Required
  NSDictionary * userInfo = notification.request.content.userInfo;
    NSLog(@"呵呵呵呵%@",userInfo);
  if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
    [JPUSHService handleRemoteNotification:userInfo];
  }
  completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有 Badge、Sound、Alert 三种类型可以选择设置
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
  // Required
  NSDictionary * userInfo = response.notification.request.content.userInfo;
    NSLog(@"哈哈哈哈%@",userInfo);
  if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
    [JPUSHService handleRemoteNotification:userInfo];
  }
  completionHandler();    // 系统要求执行这个方法
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {

    NSLog(@"哈哈哈哈123");
  // Required, iOS 7 Support
  [JPUSHService handleRemoteNotification:userInfo];
  completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    NSLog(@"哈哈哈哈1234");
  // Required, For systems with less than or equal to iOS 6
  [JPUSHService handleRemoteNotification:userInfo];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}
@end
